<?php
//
// Register globals functions
//
// thanks to: http://www.phpguru.org/article.php?ne_id=60
function unregister_globals() {
    if ( ini_get('register_globals') ) {
        
        // Might want to change this perhaps to a nicer error
        if (isset($_REQUEST['GLOBALS'])) {
            die('GLOBALS overwrite attempt detected');
        }

        // Variables that shouldn't be unset
        $noUnset = array('GLOBALS',  '_GET',
                         '_POST',    '_COOKIE',
                         '_REQUEST', '_SERVER',
                         '_ENV',     '_FILES');

        $input = array_merge($_GET,    $_POST,
                             $_COOKIE, $_SERVER,
                             $_ENV,    $_FILES,
                             isset($_SESSION) ? (array)$_SESSION : array());

        foreach ($input as $k => $v) {
            if (!in_array($k, $noUnset) AND isset($GLOBALS[$k])) {
                unset($GLOBALS[$k]);
            }
        }
    } 
}

//
// Array functions
//
function array_remove($array, $value_to_delete) {
	$result = array();
	foreach ( (array)$array as $key=>$value ) {
		if ( $value != $value_to_delete ) {
			$result[$key] = $value;
		}
	}
	return $result;
}
function array_key_remove($array, $key_to_delete) {
	$isAssoc = is_associative($array);

	$result = array();
	foreach ( (array)$array as $key=>$value ) {
		if ( $key != $key_to_delete ) {
			if ( $isAssoc ) {
				$result[$key] = $value;
			} else {
				$result[] = $value;
			}
		}
	}
	return $result;
}

function is_associative($array) {
	if ( !is_array($array) || empty($array) ) {
		return false;
	}

	$keys = array_keys($array);
	return ( array_keys($keys) !== $keys );
}

function array_insert_at(&$array, $index, $value) {
	$newArray = array_slice($array, 0, $index);
	array_push($newArray, $value);
	$array = array_merge($newArray, array_slice($array, $index));
}

//
// Validation (Is) functions
//
function is_percentage($value) {
	$value = trim($value);
	return preg_match('/^[0-9]+(.[0-9]+)?%$/', $value);
}

function is_datetime($value) {
	$value = trim($value);
	return preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $value);
}

/** 
 * Substitutes a value when a null value is encountered
 */
function nvl() {
	foreach ( func_get_args() as $value ) {
		if ( !empty($value) ) {
			return $value;
		}
	}
}


function get_value($item, $index) {
	if ( is_array($item) ) {
		return $item[$index];
	} else if ( is_object($item) ) {
		return $item->{$index};
	} else {
		return null;
	}
}

//
// Date functions
//

// time_since function: based on http://code.natbat.co.uk/php/time_since.php.txt
function time_since($original, $offset) {
	// array of time period chunks
	$chunks = array(
		array(SECS_PER_YEAR, 'year'),
		array(SECS_PER_MONTH, 'month'),
		array(SECS_PER_WEEK, 'week'),
		array(SECS_PER_DAY, 'day'),
		array(SECS_PER_HOUR, 'hour'),
		array(SECS_PER_MIN, 'min'),
		array(1, 'sec')		// add support for seconds
	);
	
	// fix for offset
	$original = $original - (intval($offset) * SECS_PER_HOUR);
	$today = time();
	$since = $today - $original;
	
	// $j saves performing the count function each time around the loop
	for ( $i=0, $j=count($chunks); $i<$j; $i++ ) {
		$seconds = $chunks[$i][0];
		$name = $chunks[$i][1];
		
		// finding the biggest chunk (if the chunk fits, break)
		if ( ($count = floor($since / $seconds) ) != 0 ) {
			// DEBUG print "<!-- It's $name -->\n";
			break;
		}
	}
	
	$print = ( $count == 1 ) ? '1 '.$name : "$count {$name}s";
	
/*	if ( $i + 1 < $j ) {
		// now getting the second item
		$seconds2 = $chunks[$i + 1][0];
		$name2 = $chunks[$i + 1][1];
		
		// add second item if it's greater than 0
		if ( ( $count2 = floor(($since - ($seconds * $count)) / $seconds2) ) != 0 ) {
			$print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
		}
	}*/
	
	return $print .' ago';	
}

// str to time in GMT
function gmstrtotime($str) {
   $time = strtotime($str);
   $offset = intval( date("O") ) / 100;
   $time = $time + ( $offset * SECS_PER_HOUR );
   return $time;
}

//GMT formatter 
function formatGMT($utc_offset){
	if (empty($utc_offset)){
		$gmt = "+0";
	} else {
		($utc_offset<0) ? $gmt = "-" : $gmt = "+";
		if (abs($utc_offset)<10) $gmt .= "0";
	}
	$gmt .= abs($utc_offset).":00";
	//Always returns format [-|+]99:99
	return $gmt;
}

// like strcmp, but for hosts
function hostcmp($host1, $host2, $ignore_www=true) {
	if ( $ignore_www ) {
		return strcasecmp(preg_replace('/^www\./i', '', $host1), preg_replace('/^www\./i', '', $host2));
	} else {
		return strcasecmp($host1, $host2);
	}
}
?>
